package com.course.model.service;

import com.course.model.entity.${Entity};
import com.course.model.entity.${Entity}Example;
import com.course.model.dto.${Entity}Dto;
import com.course.model.dto.PageDto;
import com.course.model.mapper.${Entity}Mapper;
import com.course.model.util.CopyUtil;
import com.course.model.util.UuidUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;
import org.apache.commons.lang3.StringUtils;

import javax.annotation.Resource;
import java.util.List;
<#list typeSet as type>
    <#if type=='Date'>
import java.util.Date;
    </#if>
</#list>

@Service
public class ${Entity}Service {

    @Resource
    private ${Entity}Mapper ${entity}Mapper;

    /**
     * 列表查询
     */
    public void list(PageDto pageDto) {
        PageHelper.startPage(pageDto.getPage(), pageDto.getSize());
        ${Entity}Example ${entity}Example = new ${Entity}Example();
        <#list fieldList as field>
            <#if field.nameHump=='sort'>
        ${entity}Example.setOrderByClause("sort asc");
            </#if>
        </#list>
        List<${Entity}> ${entity}List = ${entity}Mapper.selectByExample(${entity}Example);
        PageInfo<${Entity}> pageInfo = new PageInfo<>(${entity}List);
        pageDto.setTotal(pageInfo.getTotal());
        List<${Entity}Dto> ${entity}DtoList = CopyUtil.copyList(${entity}List, ${Entity}Dto.class);
        pageDto.setList(${entity}DtoList);
    }

    /**
     * 保存，id有值时更新，无值时新增
     */
    public void save(${Entity}Dto ${entity}Dto) {
        ${Entity} ${entity} = CopyUtil.copy(${entity}Dto, ${Entity}.class);
        if (StringUtils.isBlank(${entity}Dto.getId())) {
            this.insert(${entity});
        } else {
            this.update(${entity});
        }
    }

    /**
     * 新增
     */
    private void insert(${Entity} ${entity}) {
        <#list typeSet as type>
            <#if type=='Date'>
        Date now = new Date();
            </#if>
        </#list>
        <#list fieldList as field>
            <#if field.nameHump=='createdAt'>
        ${entity}.setCreatedAt(now);
            </#if>
            <#if field.nameHump=='updatedAt'>
        ${entity}.setUpdatedAt(now);
            </#if>
        </#list>
        ${entity}.setId(UuidUtil.getShortUuid());
        ${entity}Mapper.insert(${entity});
    }

    /**
     * 更新
     */
    private void update(${Entity} ${entity}) {
        <#list fieldList as field>
            <#if field.nameHump=='updatedAt'>
        ${entity}.setUpdatedAt(new Date());
            </#if>
        </#list>
        ${entity}Mapper.updateByPrimaryKey(${entity});
    }

    /**
     * 删除
     */
    public void delete(String id) {
        ${entity}Mapper.deleteByPrimaryKey(id);
    }
}
